package org.apache.lucene.ocean;

import java.io.IOException;
import java.util.HashSet;

import org.apache.lucene.store.instantiated.InstantiatedIndex;
import org.apache.lucene.store.instantiated.InstantiatedIndexReader;

/**
 * Simulates a multiple version IndexReader with InstantiatedIndexReader by
 * having documents over the set maxDoc be deleted.
 * 
 */
public class OceanInstantiatedIndexReader extends InstantiatedIndexReader implements Cloneable {
  private HashSet<Integer> deletedDocs;

  public OceanInstantiatedIndexReader(InstantiatedIndex index) {
    super(index);
    this.deletedDocs = new HashSet<Integer>();
  }

  public OceanInstantiatedIndexReader(InstantiatedIndex index, HashSet<Integer> deletedDocs) {
    super(index);
    this.deletedDocs = deletedDocs;
  }

  protected void doDelete(int docNum) throws IOException {
    deletedDocs.add(docNum);
  }

  public synchronized Object clone() {
    return new OceanInstantiatedIndexReader(getIndex(), (HashSet<Integer>)deletedDocs.clone());
  }
  /**
  protected void doSetNorm(int doc, String field, byte value) throws IOException {
    if (updatedNormsByFieldNameAndDocumentNumber == null) {
      updatedNormsByFieldNameAndDocumentNumber = new HashMap<String,List<NormUpdate>>(normsByFieldNameAndDocumentNumber.size());
    }
    List<NormUpdate> list = updatedNormsByFieldNameAndDocumentNumber.get(field);
    if (list == null) {
      list = new LinkedList<NormUpdate>();
      updatedNormsByFieldNameAndDocumentNumber.put(field, list);
    }
    list.add(new NormUpdate(doc, value));
  }

  public byte[] norms(String field) throws IOException {
    byte[] norms = normsByFieldNameAndDocumentNumber.get(field);
    if (updatedNormsByFieldNameAndDocumentNumber != null) {
      norms = norms.clone();
      List<NormUpdate> updated = updatedNormsByFieldNameAndDocumentNumber.get(field);
      if (updated != null) {
        for (NormUpdate normUpdate : updated) {
          norms[normUpdate.doc] = normUpdate.value;
        }
      }
    }
    return norms;
  }

  public void norms(String field, byte[] bytes, int offset) throws IOException {
    byte[] norms = normsByFieldNameAndDocumentNumber.get(field);
    System.arraycopy(norms, offset, bytes, 0, norms.length);
  }
  **/
  public int numDocs() {
    return maxDoc() - deletedDocs.size();
  }

  public boolean isDeleted(int n) {
    if (deletedDocs != null && deletedDocs.contains(n))
      return true;
    return false;
  }

  public boolean hasDeletions() {
    return deletedDocs != null && deletedDocs.size() > 0;
  }
}
